package com.yicong.ants.ui.main;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.blankj.utilcode.util.BarUtils;
import com.cchao.simplelib.core.AndroidHelper;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.model.event.CommonEvent;
import com.cchao.simplelib.ui.activity.BaseActivity;
import com.cchao.simplelib.ui.web.BackAble;
import com.cchao.simplelib.util.StringHelper;
import com.cqyc.imview.MessageMusicUtils;
import com.cqyc.network.Response;
import com.cqyc.network.getid.GetMyInformationBox;
import com.cqyc.network.http.HttpUtil;
import com.cqyc.network.model.ConfigInfo;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.tencent.imsdk.v2.V2TIMAdvancedMsgListener;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.qcloud.tuikit.tuichat.util.ChatMessageParser;
import com.x.livesdk.LiveActivity;
import com.yicong.ants.App;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.global.ClientConfig;
import com.yicong.ants.manager.AppHelper;
import com.yicong.ants.manager.BusinessHelper;
import com.yicong.ants.manager.CopyHelper;
import com.yicong.ants.manager.RouterHelper;
import com.yicong.ants.manager.RpHelper;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.ad.AdManager;
import com.yicong.ants.manager.business.Dialogs;
import com.yicong.ants.manager.config.ZzConfigs;
import com.yicong.ants.ui.me.UserInfoActivity;
import com.yicong.ants.ui.present.ExchangeYcActivity;
import com.yicong.ants.utils.InitUtil;

import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;

import java.util.ArrayList;
import java.util.List;

import cn.jiguang.jmlinksdk.api.JMLinkAPI;
import retrofit2.Call;
import retrofit2.Callback;

/**
 * 首页
 *
 * @author cchao
 */
public class MainConfigActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {
    RadioGroup mRadioGroup;
    List<Pair<RadioButton, Fragment>> mRadioRelateArr = new ArrayList<>();
    private Fragment mCurrentFragment;
    private View view;
    private MessageMusicUtils musicUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!InitUtil.INSTANCE.isInit()) {// 长期在后台，再次进入后需要重新初始化
            InitUtil.INSTANCE.init(this);
        }
        musicUtils = new MessageMusicUtils(this);
        AppHelper.transStatus(getWindow());
        BarUtils.setStatusBarLightMode(this, false);
        setContentView(R.layout.main_config_activity);
        //初始化控件
        initView();
        if (UserManager.getUserBean() != null) {
            UserManager.updateUserBean(UserManager.getUserBean());
        }
        UserManager.refreshUserInfo();
        handleJpushLink();
        handleLink();
        updateNotice();
    }

    /**
     * jpush 魔链
     */
    void handleJpushLink() {
        //首先注册回调接口
        JMLinkAPI.getInstance().register(obj -> {
            //
            Logs.e("main handleMLink", "replay = "
                    + obj.paramMap + " " + obj.uri + " " + obj.source + " " + obj.type);
        });
    }

    private Dialog showConfirmDialog;

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (event.getCode()) {
            case Constants.Event.Config_Update:
                updateNotice();
                break;
            case Constants.Event.Main_Tab_Turn:
                //有可能是空
                int index = Integer.parseInt(StringHelper.isEmpty(event.getContent()) ? "0" : event.getContent());
                mRadioGroup.check(mRadioRelateArr.get(index).getLeft().getId());
                break;
            case Constants.Event.To_Auth:
                // 要求二次确认
//                Dialogs.showCommonWarning(App.mLifecycleCallListener.mTopActivity, event.getContent(), () -> {
//                    Router.turnTo(mContext, UserInfoActivity.class)
//                            .putExtra(Constants.Extra.To_Auth, true)
//                            .start();
//                });
                if (showConfirmDialog == null || !showConfirmDialog.isShowing()) {
                    showConfirmDialog =  UiHelper.showConfirmDialog(App.mLifecycleCallListener.mTopActivity, "观看提示", "您还没有实名认证，无法开启任务，是否前往认证？", (dialog, which) -> {
                        if (which == DialogInterface.BUTTON_POSITIVE) {
                            Router.turnTo(mContext, UserInfoActivity.class).start();
                        }else{
                            if (App.mLifecycleCallListener.mTopActivity instanceof ExchangeYcActivity) {
                                App.mLifecycleCallListener.mTopActivity.finish();
                            }
                        }
                    });
                }
                break;
            case Constants.Event.Bio_Auth:
                // 立即认证
                Dialogs.showRpDialog(App.mLifecycleCallListener.mTopActivity, event.getContent(), (dialogInterface, which) -> {
                    if (which == dialogInterface.BUTTON_POSITIVE) {
                        RpHelper.startVerify((BaseActivity) App.mLifecycleCallListener.mTopActivity);
                    }
                });
                break;
            case Constants.Event.Ad_Click_Tip:
                Dialog dialog = new AlertDialog.Builder(App.mLifecycleCallListener.mTopActivity)
                        .setView(R.layout.ad_click_tip_activity)
                        .setCancelable(false)
                        .show();
                dialog.findViewById(R.id.confirm).setOnClickListener(v -> dialog.dismiss());
                break;
            case Constants.Event.To_Vide:
                RadioButton childAt = (RadioButton) mRadioGroup.getChildAt(1);
                childAt.setChecked(true);
                break;
            case Constants.Event.ENTER_ROOM:
                if (!UserManager.isLogin()) {
                    UserManager.routeLogin(this);
                }
                LiveActivity.Companion.start(thisActivity, event.getContent(), true);
                break;
        }
    }

    private void updateNotice() {
        ClientConfig config = ZzConfigs.getClientConf();
        boolean isShowedLayer = Dialogs.showNotice(this, config.getNotice());
        if (isShowedLayer) {
            return;
        }

        isShowedLayer = Dialogs.showActivity(this, config.getActivity());
        if (isShowedLayer) {
            return;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        BusinessHelper.uploadVids(mDisposable);
    }

    @Override
    protected void onStart() {
        super.onStart();
        BusinessHelper.uploadVids(mDisposable);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (UserManager.isLogin()) {
            initMusic();
        }
        RxHelper.timerConsumer(500, aLong -> {
            //
            CopyHelper.router(thisActivity);
        });
        AdManager.preloadInterstitialOnly(this);
    }

    private void initMusic() {
        HttpUtil.api.getConfigInfo("").enqueue(new Callback<Response<ConfigInfo>>() {
            @Override
            public void onResponse(Call<Response<ConfigInfo>> call, retrofit2.Response<Response<ConfigInfo>> response) {
                if (response.isSuccessful()) {
                    if (response.body() != null && response.body().getCode() == 2000) {
                        GetMyInformationBox.INSTANCE.setConfigInfo(response.body().getData());
                    }
                }
            }

            @Override
            public void onFailure(Call<Response<ConfigInfo>> call, Throwable t) {

            }
        });
        V2TIMManager.getMessageManager().removeAdvancedMsgListener(advancedMsgListener);
        V2TIMManager.getMessageManager().addAdvancedMsgListener(advancedMsgListener);
    }

    private final V2TIMAdvancedMsgListener advancedMsgListener = new V2TIMAdvancedMsgListener() {
        @Override
        public void onRecvNewMessage(V2TIMMessage msg) {
            if (msg != null) {
                if (msg.getCustomElem() != null) {
                    if (ChatMessageParser.isTyping(msg.getCustomElem().getData())) {
                        // 忽略正在输入，它不能作为真正的消息展示
                        return;
                    }
                }
                if (GetMyInformationBox.INSTANCE.getConfigInfo() != null &&
                        GetMyInformationBox.INSTANCE.getConfigInfo().getNewMessageSound() == 1) {
                    musicUtils.messageMusic(msg.getUserID());
                }
            }
        }
    };

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        handleLink();
        try {
            handleJPushIntent(intent);
        } catch (Exception ignored) {

        }
    }

    private void handleJPushIntent(Intent intent) {
        String messageJson = intent.getExtras().getString("JMessageExtra");
        JsonObject messageObject = JsonParser.parseString(messageJson).getAsJsonObject();
        JsonObject extrasObject = messageObject.get("n_extras").getAsJsonObject();
    }

    private void handleLink() {
        // 剪切板有路由跳转
        if (CopyHelper.router(thisActivity)) {
            return;
        }
        Intent intent = getIntent();
        if (intent == null) {
            return;
        }
        Logs.d("handleLink " + intent.getData());

        Uri uri = intent.getData();
        if (uri == null || uri.getHost() == null) {
            return;
        }

        RouterHelper.router(thisActivity, uri.toString());
    }

    private void initView() {
        view = findViewById(R.id.view);
        // radio
        mRadioGroup = findViewById(R.id.home_radio_group);
        mRadioGroup.removeAllViews();
        mRadioGroup.setOnCheckedChangeListener(this);
        for (Triple<Integer, String, Fragment> triple : ZzConfigs.mHomeFragment) {
            RadioButton radioButton = (RadioButton) mLayoutInflater.inflate(R.layout.home_radio_item, mRadioGroup, false);
            radioButton.setText(triple.getMiddle());
            radioButton.setId(View.generateViewId());
            mRadioRelateArr.add(Pair.of(radioButton, triple.getRight()));
            setRadioButtonSelectColor(radioButton, false);
            mRadioGroup.addView(radioButton);
        }
        setRadioDrawableVideoMode(false);
        updateRadioTextColor(false);
        mRadioGroup.check(mRadioRelateArr.get(0).getLeft().getId());
    }

    private void setRadioDrawableVideoMode(boolean videoMode) {
        if (videoMode && !ZzConfigs.getClientConf().isNewYear()) {
            for (int i = 0; i < mRadioRelateArr.size(); i++) {
                RadioButton radioButton = mRadioRelateArr.get(i).getLeft();
                int resId = R.drawable.tab_home_video_mode;
                switch (i) {
                    case 0:
                        resId = R.drawable.tab_home_video_mode;
                        break;
                    case 1:
                        resId = R.drawable.tab_video_video_mode;
                        break;
                    case 2:
                        resId = R.drawable.tab_me_video_mode;
                        break;
                }
                Drawable drawable = UiHelper.getDrawable(resId);
                radioButton.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
            }
        } else {
            for (int i = 0; i < mRadioRelateArr.size(); i++) {
                RadioButton radioButton = mRadioRelateArr.get(i).getLeft();
                Drawable drawable = UiHelper.getDrawable(ZzConfigs.mHomeFragment.get(i).getLeft());
                radioButton.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
            }
        }
    }

    private void updateRadioTextColor(boolean videoMode) {
        for (int i = 0; i < mRadioGroup.getChildCount(); i++) {
            setRadioButtonSelectColor((RadioButton) mRadioGroup.getChildAt(i), videoMode);
        }
    }

    protected void setRadioButtonSelectColor(RadioButton radioButton, boolean videoMode) {
        int textColor = R.color.new_text_color_1;
        if (videoMode) {
            textColor = R.color.new_text_color_3;
        }
        Drawable drawable = radioButton.getCompoundDrawables()[1];
        if (AndroidHelper.versionThanLOLLIPOP()) {
            drawable.setTintList(null);
        }
        if (radioButton.isChecked()) {
            textColor = R.color.themeColor;
            if (videoMode) {
                textColor = R.color.white;
            }
            if (AndroidHelper.versionThanLOLLIPOP()) {
//                drawable.setTint(UiHelper.getColor(R.textColor.themeColor1));
            }
        }
        radioButton.setTextColor(UiHelper.getColor(textColor));
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkId) {
        FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();
        Fragment toFragment = null;
        for (Pair<RadioButton, Fragment> pair : mRadioRelateArr) {
            if (pair.getLeft().getId() == checkId) {
                AppHelper.mCurMainTabIndex = mRadioRelateArr.indexOf(pair);
                RxBus.get().postEvent(Constants.Event.Main_Tab_Checked);
                toFragment = pair.getRight();
                break;
            }
        }
        //视频页面背景变黑
        if (checkId == 2) {
            view.setBackgroundColor(getResources().getColor(R.color.black));
            mRadioGroup.setBackgroundColor(getResources().getColor(R.color.black));
            BarUtils.setNavBarColor(this, Color.BLACK);
            setRadioDrawableVideoMode(true);
            updateRadioTextColor(true);
        } else {
            view.setBackgroundColor(getResources().getColor(R.color.line_ddd));
            mRadioGroup.setBackgroundColor(Color.TRANSPARENT);
            BarUtils.setNavBarColor(this, Color.parseColor("#E6FFFFFF"));
            setRadioDrawableVideoMode(false);
            updateRadioTextColor(false);
        }
        switchContent(toFragment);
        beginTransaction.commitAllowingStateLoss();
    }

    public void switchContent(Fragment to) {
        if (mCurrentFragment == to) {
            return;
        }
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (mCurrentFragment == null) {
            transaction.replace(R.id.fl_content, to).commitAllowingStateLoss();
        } else if (!to.isAdded()) {
            transaction.hide(mCurrentFragment).add(R.id.fl_content, to).commitAllowingStateLoss();
        } else {
            transaction.hide(mCurrentFragment).show(to).commitAllowingStateLoss();
        }
//        if (AndroidHelper.versionThanM()) {
//            if (to == ZzConfigs.mHomeFragment.get(ZzConfigs.mHomeFragment.size() - 1).getRight()) {
//                UiHelper.transparentStatusBar(getWindow());
//            }
//            if (mCurrentFragment == ZzConfigs.mHomeFragment.get(ZzConfigs.mHomeFragment.size() - 1).getRight()) {
//                UiHelper.setStatusBarColor(getWindow(), UiHelper.getColor(R.color.themeColor1));
//            }
//        }
        mCurrentFragment = to;
    }

    /**
     * 双击返回键退出
     */
    boolean mIsExit;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        for (int i = 0; i < fragments.size(); i++) {
            Fragment fragment = fragments.get(i);
            if (fragment instanceof BackAble) {
                if (((BackAble) fragment).onBackPressed()) {
                    return true;
                }
            }
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mIsExit) {
                finish();
                finishAffinity();
                System.exit(0);
                return true;
            }
            showToast("再按一次退出");
            mIsExit = true;
            new Handler().postDelayed(() -> mIsExit = false, 2000);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
